<template>
  <view class="search-container">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <!-- 客服图标 -->
    <onlineService></onlineService>
    <view class="container">
      <NoticeNav v-if='drawTask' text='分享以下任意商品完成任务'></NoticeNav>
      <itemParse v-if="categoryName == '不凡甄选'" :identifier.sync="identifier" :preview.sync="preview"></itemParse>
      <view class="pb120" v-if="list.length > 0">
        <!--矩阵商品列表模块-->
        <view class="pb60">
          <productGridList ref="childItem" :list.sync="list" :listResult.sync="listResult1" :hasMore.sync="hasMore"
            :isAppend.sync="isAppend" :purchasetype.sync="purchasetype" :finishLoadFlag.sync="finishLoadFlag"
            :categoryName.sync="categoryName" :groupId.sync="customerGroupId" :cateCode="cateCode"
            :bannerItemsArr.sync="bannerItemsArr" :bannerPosition.sync="bannerPosition"
            :footerBannerPosition.sync="footerBannerPosition" :type="type" :drawTask='drawTask'></productGridList>
        </view>
        <view class="pb60">
          <productGridList ref="childItem" :list.sync="list" :listResult.sync="listResult2" :hasMore.sync="hasMore"
            :isAppend.sync="isAppend" :purchasetype.sync="purchasetype" :finishLoadFlag.sync="finishLoadFlag"
            :categoryName.sync="categoryName" :groupId.sync="customerGroupId" :cateCode="cateCode"
            :bannerItemsArr.sync="bannerItemsArr" :bannerPosition.sync="bannerPosition"
            :footerBannerPosition.sync="footerBannerPosition" :type="type" :drawTask='drawTask'></productGridList>
        </view>
      </view>
      <block v-if="filterChecked.fliterCmsFooterBanner(bannerPosition)">
        <bannerPlugin :bannerItemsArr.sync="bannerItemsArr" :footerBannerPosition.sync="footerBannerPosition">
        </bannerPlugin>
      </block>
      <block v-else>
        <view v-if="hasMore > 0" class="hasMore">已到页面底部</view>
      </block>
      <!--加载更多时动画-->
      <loadMore :show.sync="showLoading" message="加载中"></loadMore>
      <!--暂无数据显示-->
      <placeholder :show.sync="is_empty" message="没有相关信息"></placeholder>
    </view>
    <!-- </movable-area> -->
    <register-widget ref="registerWidgetRef" location="search" @registerSuccess='registerSuccess' />
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import {
    CART_KEY,
    SYSTEM_INFO,
    USER_SPECICAL_INFO,
    MERCHANT_INFO,
    CUSTOMER_INFO,
    LOWER_WX_VERSION
  } from '@/utils/constant';
  import FilterBar from '@/components/filterBar/filterBar';
  import ProductGridList from '@/components/productGridList/productGridList';
  import LoadMore from '@/components/common/loadMore';
  import Placeholder from '@/components/common/placeholder';
  import NavBar from '@/components/common/navbar';
  import itemParse from '../../components/wxparse/wxparse';
  import onlineService from '@/components/common/onlineService';
  import Loading from '@/components/common/loading';
  import TabBar from '@/components/common/tabbar';
  // import category from '@/components/category/category';
  import NoticeNav from './noticeNav.vue';
  import cmsMethods from '@/utils/cmsItems.js';
  import registerWidget from "@/components/register/register-widget.vue"
  export default {
    config: {
      navigationBarTitleText: '搜索',
      navigationStyle: 'custom'
    },
    components: {
      navBar: NavBar,
      filterBar: FilterBar,
      productGridList: ProductGridList,
      loadMore: LoadMore,
      placeholder: Placeholder,
      onlineService: onlineService,
      loading: Loading,
      tabBar: TabBar,
      // category: category,
      itemParse: itemParse,
      NoticeNav: NoticeNav,
      registerWidget
    },
    data() {
      return {
        isIpx: false,
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '搜索',
          hideSearch: true,
          hideHome: false
        },
        isShowCustomNavBar: true,
        nowPages: '',
        showLoaded: false,
        type: 'category', // category/search
        categoryFixed: 0,
        isCateScroll: false,

        currentIndexNav: 0,
        hasMore: 0,
        finishLoadFlag: 0,
        list: [],
        preview: false,
        // 色块
        frontProperties: [],
        showLoading: false,
        //防止重复加载
        preventRepeatReuqest: false,
        purchasetype: 1,
        is_empty: false,
        is_filter: false,
        //当前页面
        currentPage: 1,
        //总页数
        pageTotal: 0,
        pageSize: 16,
        cateCode: '',
        classId: '',
        categoryName: '',
        navId: '',
        mainNav: '', //主分类名 （一级分类名）
        // 商户id
        merchantId: '',
        show: false,
        sort: -1,
        skuval: '',

        isShowList: 0,
        showThreeChild: 1,
        showChild: '', //是否显示三级分类     0显示 1不显示
        isSort: 1, //是否显示排序           0显示 1不显示
        isFilter: '', //是否显示筛选          0 不显示 1 显示
        isAppend: 0, // 是否显示悬浮图    0 不显示 1 显示
        threeChildcateList: [],
        windowHeight: 0,
        valueName: [],
        is_sort: '',
        color_filter: '',
        material_filter: '',
        size_filter: '',
        style_filter: '',
        // 全部的筛选数据
        colorFilter: [],
        materialFilter: [],
        sizeFilter: [],
        styleFilter: [],
        bannerContents: [],
        bannerItems: [],
        bannerPosition: [],
        bannerItemsArr: [],
        banners: [],
        footerBannerPosition: '',
        listResult: [],
        tempListLength: [],
        showGrid: true,
        showDesign: false,
        // 品牌信息 0：三仟院  1：ICH  2:PB
        brandType: getApp().globalData.brandType,
        memberLevelId: 0,
        customerGroupId: 0,
        imgurl: 'https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/%20images/none.png',
        identifier: 'cms/category_zhenxuanjianiang',
        showmessageSeach: false,
        listResult1: [],
        listResult2: [],
        afterPage: '',
        drawTask: false,
        shareImage: '',
        shareTitle: '',

      };
    },

    async onLoad(option) {
      let that = this;
      await this.$onLaunched;
      this.type = option.type || '';
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      this.isIpx = getApp().globalData.isIpx;
      this.list = [];
      this.cateCode = option.cateCode;
      this.title = decodeURIComponent(option.title) == 'extraordinarySelection' || option.title ==
        'extraordinarySelection' ? '不凡甄选' : decodeURIComponent(option.title)
      this.navbarData.navbarTitle = decodeURIComponent(option.title) == 'extraordinarySelection' || option.title ==
        'extraordinarySelection' ? '不凡甄选' : decodeURIComponent(option.title)
      this.categoryName = decodeURIComponent(option.title) == 'extraordinarySelection' || option.title ==
        'extraordinarySelection' ? '不凡甄选' : decodeURIComponent(option.title);
      if (this.type == 'task') {
        this.drawTask = true
      }
      this.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId;
      this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId;
      that.isSort = option.isSort;
      that.isFilter = option.isFilter;
      that.isAppend = option.isAppend;
      that.navId = option.navId;
      that.currentIndexNav = Number(option.currentIndexNav) || 0;
      if (this.cateCode) {
        this.getCateGoods(this.cateCode, '', '', '')
      }
      let systemInfo = uni.getStorageSync(SYSTEM_INFO);
      if (Number(systemInfo.SDKVersion) < Number(LOWER_WX_VERSION)) {
        this.isShowCustomNavBar = false;
      }
      this.windowHeight = systemInfo.windowHeight;
      that.getCurrentMerchantInfo();
      if (!!option["en"]) {
        getApp().cmsClTrack(option)
      }

      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: this.title,
      })
      if (this.categoryName == '不凡甄选') {
        // 分享小程序
        cmsMethods.getCMSPageInfo('cms/shareBuFanList', merchantInfo.cloudMerchantId, merchantInfo
          .cloudMerchantStoreId).then(res => {
          this.shareImage = res && res.shareImage,
            this.shareTitle = res && res.shareTitle
        })
      }
    },

    onShow() {
      let memberDetails = uni.getStorageSync('memberDetails');
      this.memberLevelId = memberDetails.memberLevelId || 0;
      let customerInfo = uni.getStorageSync('customerInfo');
      this.customerGroupId = customerInfo.groupId || 0;
      let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];
      let prevpage = pages[pages.length - 2];
      this.nowPages = currPage.route;
      this.getTaskInfo()
    },

    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      /**
       * 获取分类商品列表
       */
      getTaskInfo() {
        this.$commonFunction.setInitTaskCenter().then(async () => {
          let info = await getApp().getTaskInfo()
          let list = info && info.contentList[0].content
          if (info && list.length > 0) {
            this.identifier = 'cms/category_taskCenter'
          } else {
            this.identifier = 'cms/category_zhenxuanjianiang'
          }
        }).catch(() => {
          this.identifier = 'cms/category_zhenxuanjianiang'
        })
      },
      getCateGoods: async function(class_id, merchant_id, store_id, is_sort) {
        let that = this;
        let memberDetails = uni.getStorageSync('memberDetails') || getApp().globalData.memberDetails;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
        let customerInfo = uni.getStorageSync('customerInfo');
        // let merchant_id = merchantInfo.cloudMerchantId;
        let after = that.currentPage == 1 ? '' : that.afterPage
        that.$commonFunction.doSearchGoods(class_id, '', that.currentPage, that.pageSize, after, '', is_sort, '',
          '', '', '').then((res) => {
          that.afterPage = res.data.afterPage
          that.list = [...that.list, ...res.data.content];
          if (that.currentPage == 1) {
            that.list = res.data.content
          }
          let itemsList = res.data;
          that.page_total = Math.ceil(res.data.total / that.pageSize);
          // 判断是否显示已加载全部数据
          if (that.page_total == that.currentPage) {
            this.hasMore = 1;
          } else {
            this.hasMore = 0;
          }
          // 策略价格
          var s_item = [];
          for (var i in that.list) {
            s_item = that.list[i];
            if (!!that.list[i].strategies) {
              that.$commonFunction.priceRulesDeal(that.list[i].strategies, that.list[i].itemCode).then((res) => {
                if (res.price !== 0) {
                  that.list.map(itey => {
                    if (itey.itemCode == res.itemCode) {
                      itey.price = res.price
                    }
                  })
                }
                if (res.rulesArr.length > 0) {
                  that.list.map(itey => {
                    if (itey.itemCode == res.itemCode) {
                      itey.rulesArr = res.rulesArr
                    }
                  })
                }
              }).catch(err => {

              })

            }

            var customPromotionTags = [];
            var isForwardpurchaseGoods = false;
            for (var t in s_item['promotionTagList']) {
              var tagItem = s_item['promotionTagList'][t];
              if (tagItem.promotionType == 'custom_tag') {
                customPromotionTags.push(tagItem);
              }

              if (tagItem.promotionType == 'forward_purchase') {
                isForwardpurchaseGoods = true;
              }
            }

            let tempTagList = customPromotionTags.slice();
            tempTagList.sort((a, b) => {
              return a.sortOrder - b.sortOrder;
            });

            that.list[i]['customPromotionTags'] = tempTagList;
            that.list[i]['isForwardpurchaseGoods'] = isForwardpurchaseGoods;
          }

          //重新组合包含banner的商品列表
          that.newList();
        }).catch((err) => {
          that.handleShowTextToast(err.msg)
        })
        // 获取商品列表
        // const json = await api.getGoodsList({
        //   query: {
        //     class_id: class_id || '',
        //     page_no: that.currentPage,
        //     page_size: that.pageSize,
        //     merchant_id: merchantInfo.cloudMerchantId || merchant_id,
        //     store_id: merchantInfo.cloudMerchantStoreId || store_id,
        //     is_sort: is_sort,
        //     group_id: memberDetails.customerGroupId || 0,
        //     member_level_id: memberDetails.memberLevelId || 0,
        //     member_status: memberDetails.isActive || 'Inactive'
        //   }
        // });
        // if (json.code === 1000) {
        //   that.list = [...that.list, ...json.data.content];
        //   if (that.currentPage == 1) {
        //     that.list = json.data.content
        //   }
        //   let itemsList = json.data;
        //   that.page_total = Math.ceil(json.data.total / that.pageSize);
        //   // 判断是否显示已加载全部数据
        //   if (that.page_total == that.currentPage) {
        //     this.hasMore = 1;
        //   } else {
        //     this.hasMore = 0;
        //   }
        //   // 策略价格
        //   var s_item = [];
        //   for (var i in that.list) {
        //     s_item = that.list[i];
        //     if (!!that.list[i].strategies) {
        //       let result = await getApp().priceRulesDeal(that.list[i].strategies);
        //       if (result.price !== 0) {
        //         that.list[i].price = result.price;
        //       }
        //       if (result.rulesArr.length > 0) {
        //         that.list[i].rulesArr = result.rulesArr;
        //       }
        //     }

        //     var customPromotionTags = [];
        //     var isForwardpurchaseGoods = false;
        //     for (var t in s_item['promotionTagList']) {
        //       var tagItem = s_item['promotionTagList'][t];
        //       if (tagItem.promotionType == 'custom_tag') {
        //         customPromotionTags.push(tagItem);
        //       }

        //       if (tagItem.promotionType == 'forward_purchase') {
        //         isForwardpurchaseGoods = true;
        //       }
        //     }

        //     let tempTagList = customPromotionTags.slice();
        //     tempTagList.sort((a, b) => {
        //       return a.sortOrder - b.sortOrder;
        //     });

        //     that.list[i]['customPromotionTags'] = tempTagList;
        //     that.list[i]['isForwardpurchaseGoods'] = isForwardpurchaseGoods;
        //   }

        //   that.showLoaded = false;
        //   //重新组合包含banner的商品列表
        //   that.newList();
        // } else {
        //   that.showLoaded = false;
        // }
      },

      newList: async function() {
        let that = this;
        let tempList = that.list;
        let tempBannerPosition = that.bannerPosition;
        let tempArr = [];
        // for(let i in tempList){
        for (var i = 0; i < tempList.length; i++) {
          //去重
          for (var j = i + 1; j < tempList.length; j++) {
            if (tempList[i].itemId !== undefined && tempList[j].itemId !== undefined) {
              if (tempList[i].itemId == tempList[j].itemId && tempList[i].valueId == tempList[j].valueId) {
                //第一个等同于第二个，splice方法删除第二个
                tempList.splice(j, 1);
                j--;
              }
            }
          }
          if (tempBannerPosition.indexOf(parseInt(i)) !== -1) {
            if (that.tempListLength.indexOf(parseInt(i)) == -1) {
              var p = 0;
              for (let b in tempBannerPosition) {
                if (tempBannerPosition[b] < i) {
                  if (tempBannerPosition[b] > 1) {
                    p++;
                  }
                }
              }

              if (i > 1) {
                tempList.splice(parseInt(i) + p, 0, that.bannerItemsArr[i]);
              } else {
                tempList.splice(parseInt(i) - 1, 0, that.bannerItemsArr[i]);
              }
              tempArr.push(parseInt(i));
            }
          }
        }
        that.tempListLength = [...that.tempListLength, ...tempArr];
        that.listResult = [...that.listResult, ...tempList];


        that.listResult = tempList;
        let arr = that.listResult
        for (var i = 0; i < arr.length; i++) {
          if (i % 2 == 0) {
            that.listResult1.push(arr[i])
          } else {
            that.listResult2.push(arr[i])
          }
        }

        that.showLoaded = false;
        that.$forceUpdate();
      },

      // 判断是否有merchantInfo,没有则重新请求
      getCurrentMerchantInfo: async function() {
        let that = this;
        var merchantInfo = uni.getStorageSync(MERCHANT_INFO) || '';
        this.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId || '';
        this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId || '';

        if (merchantInfo) {
          if (this.cateCode != undefined && this.cateCode.length > 0) { //分类进入
            this.showLoaded = true;
          } else { //搜索进入

          }
        } else {
          // 获取商户信息
          const accountInfo = uni.getAccountInfoSync(); // 小程序appId
          var merchantInfo = await api.merchantInfo(accountInfo.miniProgram.appId);
          if (merchantInfo.code === 200) {
            // 存储商户信息
            uni.setStorageSync(MERCHANT_INFO, merchantInfo.data);
            that.storeId = merchantInfo.data.cloudMerchantStoreId;
            that.merchantId = merchantInfo.data.cloudMerchantId;
            if (this.cateCode != undefined && this.cateCode.length > 0) { //分类进入
              this.showLoaded = true;
            } else { //搜索进入

            }

          }
        }
      },

      //加载更多
      onReachBottom() {
        let that = this;
        that.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId;
        that.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId;
        that.showLoading = true;
        //判断总页数是否大于翻页数
        if (that.page_total > that.currentPage) {
          //防止重复加载
          if (that.preventRepeatReuqest) {
            return true;
          }
          that.preventRepeatReuqest = true;
          that.currentPage++;
          let classId = '';
          if (this.cateCode != undefined) {
            classId = this.cateCode;
          }
          if (classId != '') {
            this.getCateGoods(classId, '', '', '')
          }
          that.preventRepeatReuqest = false;
        } else {
          that.showLoading = false;
        }
      },

      /**
       * 监听页面滑动事件
       */
      onPageScroll: function(Object) {
        var that = this;
      },

      // 按排序显示商品列表
      currentType(obj) {
        this.list = [];
        this.currentPage = 1;
        this.is_sort = obj.is_sort;
        this.is_empty = false;
        this.show = false;
        this.doSearchGoods(this.cateCode, '', '', this.storeId, this.defaultKeyword, this.is_sort, this.color_filter,
          this.material_filter, this.size_filter, this.style_filter);
      },

      // 按筛选条件排序
      arrowType(obj) {
        this.color_filter = obj.color_filter;
        this.material_filter = obj.material_filter;
        this.size_filter = obj.size_filter;
        this.style_filter = obj.style_filter;
        this.list = [];
        this.currentPage = 1;
        this.doSearchGoods(this.cateCode, '', '', this.storeId, this.defaultKeyword, this.is_sort, this.color_filter,
          this.material_filter, this.size_filter, this.style_filter);
      },
      onShareAppMessage: function(res) {
        // 分享卡片图片
        let memberCode = uni.getStorageSync('memberCode') || '';
        let sharePath = '/pages/item/search?cateCode=' + this.cateCode + '&title=' + this.title
        let pageTitle = this.shareTitle || uni.getStorageSync('storeName');
        let shareImageUrl = this.shareImage || '';
        if (res.from === 'button') {
          // 来自页面内转发按钮
          // console.log(res.target)
        }
        // console.log(res.from, pageTitle, sharePath, this.shareImage)
        this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
        this.$commonSensors.sensorsPageShare()
				this.$sr.setContext({ share_title: pageTitle || 'THE MACALLAN EBOUTIQUE麦卡伦' });
        return this.$commonFunction.commonShare(res, pageTitle, sharePath, shareImageUrl);
      }
    },
    // onShareTimeline() {
    //   return {
    //     title: uni.getStorageSync('storeName') || '小程序商城',
    //     query: '/pages/item/search?cateCode=' + this.cateCode + '&title=' + this.title
    //   };
    // }
  };
</script>

<style lang="less">
  .wx-swiper-dot {
    width: 42rpx !important;
    height: 4rpx !important;
    border-radius: 0 !important;
    margin-left: -16rpx !important;
  }

  .wx-swiper-dots {
    display: flex;
    justify-content: center;
    margin-left: 8rpx;
  }

  .fix-iphonex-button::after {
    content: ' ';
    position: fixed;
    bottom: 0 !important;
    height: auto !important;
    width: 100%;
    background: #fff;
  }

  .pb120 {
    // padding-bottom: 140rpx;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 16rpx;
    background-color: #FFFFFF;

    .pb60 {
      width: calc(50% - 8rpx);
    }
  }

  .hasMore {
    font-size: 12px;
    color: #444;
    background: #f7f5f4;
    width: 100%;
    text-align: center;
    padding-bottom: 48rpx;
    padding-top: 20rpx;
  }

  .container {
    background: #f7f5f4;
  }
</style>